import baseUrl from "./url.js"
const request = (url, data, type, loading = true) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync("token") || ''
		const httpDefaultOpts = {
			url: baseUrl.url + url,
			data,
			method: type || "POST",
			dataType: "json",
			header: {
				"x-requested-with": "XMLHttpRequest",
				"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
				"token": token,
			},
		}
		if (loading) {
			uni.showLoading({
				icon: "loading",
				mask: true
			})
		}
		uni.request(httpDefaultOpts).then(res => {
			if (res.statusCode == 200) {
				if (res.data.code == 0) { //请求成功
					uni.hideLoading()
					resolve(res.data)
				} else if (res.data.code == -2) { //token失效
					uni.removeStorageSync("token")
					uni.hideLoading()
					// uni.showToast({
					// 	title: "您还未登录",
					// 	duration: 3000,
					// 	icon: "none"
					// })
					// setTimeout(() => {
					// 	uni.redirectTo({
					// 		url: '/pages/login/login'
					// 	})
					// }, 3000)
				} else {
					resolve(res.data)
					uni.hideLoading()
					uni.showToast({
						title: res.data.msg,
						duration: 2000,
						icon: "none"
					})
				}
			} else {
				reject(res)
				uni.hideLoading()
				uni.showToast({
					title: '请求异常!',
					duration: 1500,
					icon: "none"
				})
			}
			// if (loading) {
			// 	uni.hideLoading()
			// }
		}).catch((response) => {
			reject(response)
			uni.hideLoading()
			uni.showToast({
				title: '请求失败!',
				duration: 1500,
				icon: "none"
			})
			setTimeout(() => {
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}, 1500)
		})
	})
}

export default request